package io.github.igordonxiao.gateguard.util;

import io.github.igordonxiao.gateguard.config.GuardUser;
import io.github.igordonxiao.gateguard.exception.UserExceptions;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.security.Principal;

/**
 * 用于从spring security的请求上下文中获取用户信息.
 */
public class SecurityUtils {
    private SecurityUtils() throws IllegalAccessException {
        throw new IllegalAccessException("静态不允许创建实例!");
    }


    private static HttpServletRequest request() {
        return RequestContextHolder.getRequestAttributes() == null ? null :
                ServletRequestAttributes.class.cast(RequestContextHolder.getRequestAttributes()).getRequest();
    }

    public static String getLoginUserId() throws AuthenticationException {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null) {
            Object p = authentication.getPrincipal();
            if (p instanceof GuardUser) {
                return GuardUser.class.cast(p).getId();
            }
        }
        throw UserExceptions.USER_NOT_LOGIN;
    }


    public static String getLoginUserAccessToken() throws AuthenticationException {
        HttpServletRequest request = request();
        Principal principal = request == null ? null : request.getUserPrincipal();
        if (principal == null) {
            throw UserExceptions.USER_NOT_LOGIN;
        }
        Object details = ((OAuth2Authentication) principal).getDetails();
        if (details instanceof OAuth2AuthenticationDetails) {
            return ((OAuth2AuthenticationDetails) details).getTokenValue();
        }
        throw UserExceptions.USER_NOT_LOGIN;
    }
}
